/*
描述：问题展示组件，用于显示问题列表，包括问题标题、内容、图片、作者信息和点赞数等
完成人：何艺珲
完成时间: 2025/04/26
*/

<script setup lang="ts">

import { ref, onMounted, defineProps, watch } from 'vue';
import axios from "axios";
import { useRouter } from 'vue-router';
import {Calendar} from "@element-plus/icons-vue";

const router = useRouter();

const goQuestionDetailView = (questionId: number) => {
  router.push({
    path: '/question',
    query: { id: questionId }
  });
};

const props = defineProps<{
  currentComponent: number
}>();

watch(() => props.currentComponent, (newVal) => {
  console.log('currentComponent changed to:', newVal);
  fetchQuestions();
});

interface Question {
  id: number;
  title: string;
  content: string;
  img: string;
  createtime: string;
  updatetime?: string;
  user_id: number;
  likes: number;
  username?: string;
  avatar?: string;
}


const questions = ref<Question[]>([]);

// 格式化日期函数
const formatDate = (dateString: string): string => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取问题列表数据
const fetchQuestions = async (): Promise<void> => {
  try {
    if(props.currentComponent === 0){
      const response = await axios.post('http://localhost:8089/question/getQuestionList', {
        id: '',
        title: '',
        content: '',
        img: '',
        createtime: '',
        updatetime: '',
        user_id: '',
        likes:'',
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': '*/*'
        }
      });

      if (response.data && response.data.code === 1) {
        // 处理返回的数据，确保符合Question接口
        questions.value = response.data.data.map((item: any) => ({
          ...item,
        }));

        // 获取每个问题的用户信息
        for (let i = 0; i < questions.value.length; i++) {
          await getUserInfo(questions.value[i].user_id, i);
        }

      }
    }else {
      const response = await axios.get(
          'http://localhost:8089/tag/getTagQuestion'
      , {
        headers: {
          'Content-Type': 'application/json',
          'Accept': '*/*'
        },
        params: {id: props.currentComponent},
      });

      if (response.data && response.data.code === 1) {
        // 处理返回的数据，确保符合Question接口
        questions.value = response.data.data.map((item: any) => ({
          ...item,
        }));

        // 获取每个问题的用户信息
        for (let i = 0; i < questions.value.length; i++) {
          await getUserInfo(questions.value[i].user_id, i);
        }

      }
    }
  } catch (error) {
    console.error('获取问题列表失败:', error);
  }
};




// 获取用户信息
const getUserInfo = async (userId: number, index: number): Promise<void> => {
  try {
    const options = {
      method: 'GET',
      url: 'http://localhost:8089/user/getUserInfo',
      params: {id: userId.toString()},
      headers: {
        token: '',
        Accept: '*/*',
      }
    };

    const response = await axios.request(options);
    if (response.data && response.data.code === 1) {
      // 更新问题对象中的用户信息
      questions.value[index].username = response.data.data.username;
      questions.value[index].avatar = response.data.data.avatar;
    }
  } catch (error) {
    console.error(`获取用户 ${userId} 信息失败:`, error);
  }
};

onMounted(() => {
  fetchQuestions();
});
</script>

<script lang="ts">
  export default {
    name: 'QuestionComponent'
  }
</script>

<template>
  <div class="component-container">
    <div class="content">
      <div class="question-item" v-for="(question, index) in questions" :key="index">
        <div class="question-header">
          <div class="date-display">
            <span class="calendar-icon"><el-icon><Calendar /></el-icon></span>
            {{ formatDate(question.createtime).toUpperCase() }}
          </div>
        </div>
        <div class="question-content-wrapper">
          <div class="text-content">
            <h2 class="question-title" @click="goQuestionDetailView(question.id)">{{ question.title }}</h2>
            <p class="question-content">{{ question.content }}</p>
          </div>
          <div class="img-container">
            <div class="img">
              <img :src="question.img" alt="Question Image"/>
            </div>
          </div>
        </div>
        <div class="question-footer">
          <div class="author-info">
            <div class="author-avatar">
              <img v-if="question.avatar" :src="question.avatar" alt="User Avatar" class="avatar-img"/>
              <span v-else>👤</span>
            </div>
            <div class="author-name">{{ question.username || '用户 ' + question.user_id }}</div>
          </div>

          <div class="question-meta">
            <span class="comments-count">❤ {{ question.likes || 0 }} 点赞</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.component-container {
  padding: 0 20px 0 20px;
  max-width: 100%;
  margin: 0 auto;
}



.question-item {
  border: 1px solid #e1e4e8;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 30px;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  overflow: hidden;
}

.question-header {
  margin-bottom: 16px;
}

.date-display {
  font-size: 14px;
  color: #6a737c;
  font-weight: 500;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.calendar-icon {
  margin-right: 6px;
}

.question-title {
  margin: 0 0 16px 0;
  color: #000;
  font-size: 24px;
  font-weight: 700;
  line-height: 1.3;
  cursor: pointer;
}

.question-content-wrapper {
  display: flex;
  gap: 20px;
  height: 170px;
}

.text-content {
  flex: 2;
}

.img-container {
  flex: 1;
  width: 300px;
  height: 150px;
  overflow: hidden;
  border-radius: 8px;
}

.img-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.question-content {
  margin: 0 0 15px 0;
  color: #444;
  font-size: 16px;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.question-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.author-info {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  font-size: 18px;
  overflow: hidden;
}

.avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.author-name {
  font-size: 14px;
  font-weight: 500;
  color: #444;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 16px;
}

.comments-count {
  font-size: 14px;
  color: #6a737c;
}


</style>
